{{ template "page/head_start" .}}
<style>
  body {
    background-color: #f5f7fa;
  }

  .stat-card {
    background: white;
    border-radius: 10px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    transition: all 0.3s ease;
    margin-bottom: 1.5rem;
  }

  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,.12);
  }

  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
    color: white;
  }

  .stat-icon.primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
  .stat-icon.success { background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%); }
  .stat-icon.warning { background: linear-gradient(135deg, #ffd89b 0%, #19547b 100%); }
  .stat-icon.danger { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
  .stat-icon.info { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }

  .stat-value {
    font-size: 2rem;
    font-weight: 700;
    color: #2c3e50;
    margin: 0.5rem 0 0.25rem 0;
  }

  .stat-label {
    color: #7f8c8d;
    font-size: 0.9rem;
    font-weight: 500;
  }

  .progress-bar {
    height: 8px;
    border-radius: 4px;
    margin-top: 0.5rem;
  }

  .card-header-custom {
    background: white;
    border-bottom: 2px solid #f0f0f0;
    padding: 1.25rem 1.5rem;
    font-weight: 600;
    color: #2c3e50;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .status-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 0.875rem;
    font-weight: 600;
  }

  .status-badge.running {
    background: #d4edda;
    color: #155724;
  }

  .status-badge.stopped {
    background: #f8d7da;
    color: #721c24;
  }

  .pulse {
    animation: pulse 2s infinite;
  }

  @keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
  }

  .quick-action-btn {
    width: 100%;
    padding: 1rem;
    border-radius: 10px;
    border: 2px dashed #e0e0e0;
    background: white;
    color: #667eea;
    font-weight: 600;
    transition: all 0.3s ease;
  }

  .quick-action-btn:hover {
    border-color: #667eea;
    background: #f8f9ff;
    transform: translateY(-2px);
  }

  .system-info-table {
    background: white;
    border-radius: 10px;
    overflow: hidden;
  }

  .system-info-table td {
    padding: 1rem;
    border-bottom: 1px solid #f0f0f0;
  }

  .system-info-table tr:last-child td {
    border-bottom: none;
  }

  .version-badge {
    background: #667eea;
    color: white;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 0.85rem;
    font-weight: 600;
  }
</style>
{{ template "page/head_end" .}}

{{ template "page/body_start" .}}
{{ template "component/sidebar" . }}

<div class="main-content">
  <!-- Top Navbar -->
  <nav class="navbar-top">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <h4 class="mb-0"><i class="bi bi-speedometer2 me-2"></i>{{ i18n "menu.dashboard" }}</h4>
        <small class="text-muted">{{ i18n "pages.index.welcome" }}</small>
      </div>
      <div>
        <button class="btn btn-outline-primary" id="refreshBtn">
          <i class="bi bi-arrow-clockwise me-1"></i> {{ i18n "refresh" }}
        </button>
      </div>
    </div>
  </nav>

  <div class="container-fluid px-4">
    <!-- Loading State -->
    <div id="loadingState" class="text-center py-5">
      <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;"></div>
      <p class="mt-3 text-muted">{{ i18n "loading" }}...</p>
    </div>

    <!-- Main Content -->
    <div id="mainContent" style="display: none;">
      <!-- System Stats Row -->
      <div class="row">
        <div class="col-md-3 col-sm-6">
          <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
              <div>
                <div class="stat-label">{{ i18n "pages.index.cpu" }}</div>
                <div class="stat-value" id="cpuValue">0%</div>
                <div class="progress">
                  <div class="progress-bar bg-primary" id="cpuProgress" style="width: 0%"></div>
                </div>
              </div>
              <div class="stat-icon primary">
                <i class="bi bi-cpu"></i>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-3 col-sm-6">
          <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
              <div>
                <div class="stat-label">{{ i18n "pages.index.memory" }}</div>
                <div class="stat-value" id="memValue">0%</div>
                <div class="progress">
                  <div class="progress-bar bg-success" id="memProgress" style="width: 0%"></div>
                </div>
              </div>
              <div class="stat-icon success">
                <i class="bi bi-memory"></i>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-3 col-sm-6">
          <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
              <div>
                <div class="stat-label">{{ i18n "pages.index.disk" }}</div>
                <div class="stat-value" id="diskValue">0%</div>
                <div class="progress">
                  <div class="progress-bar bg-warning" id="diskProgress" style="width: 0%"></div>
                </div>
              </div>
              <div class="stat-icon warning">
                <i class="bi bi-hdd"></i>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-3 col-sm-6">
          <div class="stat-card">
            <div class="d-flex justify-content-between align-items-start">
              <div>
                <div class="stat-label">{{ i18n "pages.index.uptime" }}</div>
                <div class="stat-value" style="font-size: 1.5rem;" id="uptimeValue">0d</div>
              </div>
              <div class="stat-icon info">
                <i class="bi bi-clock"></i>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Xray Status Card -->
      <div class="row">
        <div class="col-lg-8">
          <div class="stat-card">
            <div class="card-header-custom">
              <span><i class="bi bi-gear-wide-connected me-2"></i>Xray {{ i18n "pages.index.status" }}</span>
              <span class="status-badge running" id="xrayStatus">
                <span class="pulse">●</span>
                <span>{{ i18n "running" }}</span>
              </span>
            </div>
            <div class="p-4">
              <div class="row">
                <div class="col-md-6">
                  <h6 class="text-muted mb-3">{{ i18n "pages.index.version" }}</h6>
                  <p class="mb-0">
                    <span class="version-badge" id="xrayVersion">Loading...</span>
                  </p>
                </div>
                <div class="col-md-6">
                  <h6 class="text-muted mb-3">{{ i18n "pages.index.totalTraffic" }}</h6>
                  <p class="mb-0">
                    <i class="bi bi-arrow-up text-success me-2"></i>
                    <strong id="uploadTraffic">0 B</strong>
                    <i class="bi bi-arrow-down text-primary ms-3 me-2"></i>
                    <strong id="downloadTraffic">0 B</strong>
                  </p>
                </div>
              </div>
              <hr>
              <div class="d-flex gap-2">
                <button class="btn btn-sm btn-success" id="restartXrayBtn">
                  <i class="bi bi-arrow-clockwise me-1"></i> {{ i18n "pages.index.restart" }}
                </button>
                <button class="btn btn-sm btn-danger" id="stopXrayBtn">
                  <i class="bi bi-stop-circle me-1"></i> {{ i18n "stop" }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <div class="col-lg-4">
          <div class="stat-card">
            <div class="card-header-custom">
              <span><i class="bi bi-lightning-charge me-2"></i>{{ i18n "pages.index.quickActions" }}</span>
            </div>
            <div class="p-3">
              <button class="quick-action-btn mb-2" onclick="window.location.href='{{ .base_path }}panel/inbounds'">
                <i class="bi bi-plus-circle me-2"></i>{{ i18n "pages.inbounds.addInbound" }}
              </button>
              <button class="quick-action-btn mb-2" onclick="window.location.href='{{ .base_path }}panel/settings'">
                <i class="bi bi-gear me-2"></i>{{ i18n "menu.settings" }}
              </button>
              <button class="quick-action-btn" id="backupBtn">
                <i class="bi bi-download me-2"></i>{{ i18n "pages.index.backup" }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- System Info Table -->
      <div class="row">
        <div class="col-12">
          <div class="stat-card">
            <div class="card-header-custom">
              <span><i class="bi bi-info-circle me-2"></i>{{ i18n "pages.index.systemInfo" }}</span>
            </div>
            <div class="system-info-table">
              <table class="table table-borderless mb-0">
                <tbody>
                  <tr>
                    <td width="30%"><strong>{{ i18n "pages.index.hostname" }}</strong></td>
                    <td id="hostname">-</td>
                  </tr>
                  <tr>
                    <td><strong>{{ i18n "pages.index.os" }}</strong></td>
                    <td id="osInfo">-</td>
                  </tr>
                  <tr>
                    <td><strong>{{ i18n "pages.index.publicIP" }}</strong></td>
                    <td>
                      <span id="publicIPv4">-</span>
                      <span class="ms-3" id="publicIPv6">-</span>
                    </td>
                  </tr>
                  <tr>
                    <td><strong>TCP/UDP {{ i18n "pages.index.connections" }}</strong></td>
                    <td>
                      <span class="badge bg-primary me-2">TCP: <span id="tcpCount">0</span></span>
                      <span class="badge bg-info">UDP: <span id="udpCount">0</span></span>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

{{template "page/body_scripts" .}}
<script>
let refreshInterval;

$(document).ready(function() {
  loadData();

  // Auto refresh every 5 seconds
  refreshInterval = setInterval(loadData, 5000);

  // Refresh button
  $('#refreshBtn').on('click', function() {
    $(this).find('i').addClass('spinning');
    loadData();
    setTimeout(() => {
      $(this).find('i').removeClass('spinning');
    }, 1000);
  });

  // Xray control buttons
  $('#restartXrayBtn').on('click', restartXray);
  $('#stopXrayBtn').on('click', stopXray);
  $('#backupBtn').on('click', downloadBackup);
});

function loadData() {
  axios.post('/panel/server/status', {}, { hideLoader: true })
    .then(response => {
      if (response.data.success) {
        updateUI(response.data.obj);
        $('#loadingState').hide();
        $('#mainContent').fadeIn();
      }
    })
    .catch(error => {
      console.error('Failed to load data:', error);
    });
}

function updateUI(data) {
  // CPU
  const cpuPercent = data.cpu ? data.cpu.toFixed(1) : 0;
  $('#cpuValue').text(cpuPercent + '%');
  $('#cpuProgress').css('width', cpuPercent + '%');

  // Memory
  if (data.mem) {
    const memPercent = ((data.mem.current / data.mem.total) * 100).toFixed(1);
    $('#memValue').text(memPercent + '%');
    $('#memProgress').css('width', memPercent + '%');
  }

  // Disk
  if (data.disk) {
    const diskPercent = ((data.disk.current / data.disk.total) * 100).toFixed(1);
    $('#diskValue').text(diskPercent + '%');
    $('#diskProgress').css('width', diskPercent + '%');
  }

  // Uptime
  if (data.uptime) {
    const days = Math.floor(data.uptime / 86400);
    const hours = Math.floor((data.uptime % 86400) / 3600);
    $('#uptimeValue').text(`${days}d ${hours}h`);
  }

  // Xray Status
  if (data.xray) {
    if (data.xray.state === 'running') {
      $('#xrayStatus').removeClass('stopped').addClass('running')
        .html('<span class="pulse">●</span><span>{{ i18n "running" }}</span>');
      $('#xrayVersion').text(data.xray.version || 'Unknown');
    } else {
      $('#xrayStatus').removeClass('running').addClass('stopped')
        .html('<span>●</span><span>{{ i18n "stopped" }}</span>');
    }
  }

  // Network Traffic
  if (data.netIO) {
    $('#uploadTraffic').text(formatBytes(data.netIO.up));
    $('#downloadTraffic').text(formatBytes(data.netIO.down));
  }

  // System Info
  $('#tcpCount').text(data.tcpCount || 0);
  $('#udpCount').text(data.udpCount || 0);

  if (data.publicIP) {
    $('#publicIPv4').text(data.publicIP.ipv4 || '-');
    $('#publicIPv6').text(data.publicIP.ipv6 || '-');
  }
}

function formatBytes(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
}

function restartXray() {
  if (!confirm('{{ i18n "pages.index.restartXrayConfirm" }}')) return;

  showLoading();
  axios.post('/panel/server/restartXrayService')
    .then(response => {
      if (response.data.success) {
        showNotification('{{ i18n "pages.index.restartXraySuccess" }}', 'success');
        setTimeout(loadData, 2000);
      }
    })
    .catch(error => {
      hideLoading();
    });
}

function stopXray() {
  if (!confirm('{{ i18n "pages.index.stopXrayConfirm" }}')) return;

  showLoading();
  axios.post('/panel/server/stopXrayService')
    .then(response => {
      if (response.data.success) {
        showNotification('{{ i18n "pages.index.stopXraySuccess" }}', 'success');
        setTimeout(loadData, 2000);
      }
    })
    .catch(error => {
      hideLoading();
    });
}

function downloadBackup() {
  window.location.href = basePath + 'panel/API/db/export';
}

// Add spinning animation
$('<style>.spinning { animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>').appendTo('head');
</script>
{{ template "page/body_end" .}}
